<template>
    <el-card class="mt16">
        <!-- 信息提示 -->
        <el-alert title="添加商品信息" type="info" show-icon center :closable="false" />
        <!-- 步骤条 -->
        <el-steps class="mt16" :active="activeName" align-center>
            <el-step title="基本信息" />
            <el-step title="商品参数" />
            <el-step title="商品属性" />
            <el-step title="商品图片" />
            <el-step title="商品内容" />
            <el-step title="完成" />
        </el-steps>
        <!-- tabs栏 -->
        <el-form class="mt16" label-position="top">
            <el-tabs v-model="activeName" tab-position="left" @tab-change="tabchange" :before-leave="beforeLeave">
                <el-tab-pane label="基本信息" :name="0">
                    <el-form-item label="商品名称">
                        <el-input v-model="goodsSubmitObj.goods_name"></el-input>
                    </el-form-item>

                    <el-form-item label="商品价格">
                        <el-input type="number" v-model="goodsSubmitObj.goods_price"></el-input>
                    </el-form-item>

                    <el-form-item label="商品重量">
                        <el-input type="number" v-model="goodsSubmitObj.goods_weight"></el-input>
                    </el-form-item>

                    <el-form-item label="商品数量">
                        <el-input type="number" v-model="goodsSubmitObj.goods_number"></el-input>
                    </el-form-item>

                    <el-form-item label="商品分类">
                        <!-- 商品分类-级联选择器 -->
                        <p>{{ checkArr }}</p>
                        <el-cascader v-model="checkArr" :options="goodsCateList" :props="defaultProps"
                            @change="handleChange" />
                    </el-form-item>


                </el-tab-pane>
                <!-- 动态参数 -->
                <el-tab-pane label="商品参数" :name="1">
                    <el-form-item v-for="item in manyParamsArr" :label="item.attr_name" :key="item.attr_id">
                        <el-checkbox-group v-model="checkManyValsArr">
                            <el-checkbox v-for="(item2, index) in item.attr_vals" :key="index" :label="item2"></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                </el-tab-pane>
                <!-- 静态属性 -->
                <el-tab-pane label="商品属性" :name="2">
                    <el-form-item :label="item.attr_name" v-for="item in onlyParamsArr" :key="item.attr_id">
                        <el-input v-model="item.attr_vals"></el-input>
                    </el-form-item>
                </el-tab-pane>
                <!-- 图片上传 -->
                <el-tab-pane label="商品图片" :name="3">
                    <el-upload class="upload-demo" :action="uploadUrl" :headers="headerConfig" :on-success="handleSuccess"
                        :on-remove="handleRemove" list-type="picture">
                        <el-button type="primary">上传</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                jpg/png files with a size less than 500kb
                            </div>
                        </template>
                    </el-upload>



                </el-tab-pane>
                <el-tab-pane label="商品内容" :name="4">

                    <quill-editor v-model:value="goodsSubmitObj.goods_introduce" />
                    <el-button type="primary" class="mt16" @click="addGoodsOk">添加商品</el-button>

                </el-tab-pane>
            </el-tabs>

        </el-form>

    </el-card>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import type { CascaderProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import * as API from '@/http/api'
import type { IManyParamsType, IOnlyParamsType } from '@/dataType/index'
import { useRouter } from "vue-router";

const router = useRouter()



//添加商品
const addGoodsOk = async () => {
    //处理分类列表
    goodsSubmitObj.goods_cat = checkArr.value.join(',')
    //处理上传图片
    goodsSubmitObj.pics = JSON.parse(JSON.stringify(uploadPicArr.value))
    //处理动态参数
    const manyP = manyParamsArr.value.map(item => {
        return {
            "attr_id": item.attr_id,
            "attr_value": item.attr_vals.join(',')
        }
    })

    //处理静态参数
    const onlyP = onlyParamsArr.value.map(item => {
        return {
            "attr_id": item.attr_id,
            "attr_value": item.attr_vals
        }
    })

    //合并动态和静态参数
    goodsSubmitObj.attrs = JSON.parse(JSON.stringify([...manyP, ...onlyP]))

    //调添加商品接口，将数据传给后台
    await API.addGoodsApi(goodsSubmitObj)

    //路由跳转，重定向到商品列表，看看有没有新的商品！！！！
    router.push('/goods')

}

const uploadUrl = ref('http://www.tangxiaoyang.vip:8888/api/v2/upload')
const headerConfig = reactive({
    Authorization: localStorage.getItem('token')
})

//上传成功
const uploadPicArr = ref<{ pic: string }[]>([])
const handleSuccess = (res: any) => {
    console.log('上传成功：', res)
    const picObj = { pic: res.data.tmp_path }
    uploadPicArr.value.push(picObj)
    console.log('上传数组：', uploadPicArr.value)
}

//删除上传的图片
const handleRemove = (res: any) => {
    console.log('删除成功：', res)
    //找到要删除的图片下标
    let index = uploadPicArr.value.findIndex(item => {
        return item.pic === res.response.data.tmp_path
    })

    console.log(index)
    //再删除
    uploadPicArr.value.splice(index, 1)
}



//选定的动态参数值
const checkManyValsArr = ref<string[]>([])
onMounted(() => {
    getGoodsCateList()
})

//表单提交对象
const goodsSubmitObj = reactive({
    //商品名称
    goods_name: '',
    //商品分类
    goods_cat: '',
    goods_price: 0,
    goods_number: 0,
    goods_weight: 0,
    goods_introduce: '',
    pics: [] as { pic: string }[],
    attrs: [] as { attr_id: number, attr_value: string }[]
})

//监听离开tab之前事件
const beforeLeave = (newActive: any, oldAcive: any) => {


    //阻止的条件 从0来，并且分类必须是三级，否则阻止
    if (oldAcive === 0 && checkArr.value.length !== 3) {

        ElMessage({
            message: '您选择的分类不是三级，请重新选择',
            type: 'error'
        })

        return false;

    }
}

const getGoodsCateList = async () => {
    //调用商品分类接口
    const res = await API.getGoodsCateListApi({ type: 3 })
    console.log('分类列表111：', res)
    goodsCateList.value = res.data
}


//选中的商品分类
const checkArr = ref<number[]>([])
//商品分类
const goodsCateList = ref([])
//分类配置项
const defaultProps = reactive<CascaderProps>({
    label: 'cat_name',
    value: 'cat_id',
    children: 'children',
    expandTrigger: 'hover'
})


//改变分类触发
const handleChange = () => {

}
const activeName = ref(0)
const currentCateId = computed(() => {
    return checkArr.value.at(-1)
})

//动态参数
const manyParamsArr = ref<IManyParamsType[]>([])
//静态属性
const onlyParamsArr = ref<IOnlyParamsType[]>([])
const tabchange = async () => {
    console.log('当前tab:', activeName.value)
    if (activeName.value === 1) {
        //渲染动态参数
        const res = await API.getGoodsParamsListApi(currentCateId.value as number, 'many')
        console.log('动态参数：', res)
        res.data.forEach((item: any) => {
            item.attr_vals = item.attr_vals.length > 0 ? item.attr_vals.split(',') : []
        })

        manyParamsArr.value = res.data;


    } else if (activeName.value === 2) {
        //渲染静态参数
        const res = await API.getGoodsParamsListApi(currentCateId.value as number, 'only')
        console.log('静态参数：', res)


        onlyParamsArr.value = res.data;
    }
}

</script>

<style scoped>
@import "@/assets/public.css";

:deep(.el-step__title) {
    font-size: 14px;
}

:deep(.ql-editor) {
    height: 300px;
}
</style>